package xyz.weizhi.tanhua.appserver.interceptor;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import xyz.weizhi.commons.utils.JwtUtils;
import xyz.weizhi.tanhua.model.domain.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author milian
 * @Date 2021/10/22 0022 18:53
 */
@Log4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURL().toString();
        //log.info("当前请求路径为:{}",path);
        System.out.println("------------------------------请求地址为:"+path);
        // 获取token
        String token = request.getHeader("Authorization");
        // 判断token是否有效
        boolean verifyToken  = JwtUtils.verifyToken(token);
        // 如果token失效返回
        if (!verifyToken ){
            log.info("token失效");
            response.setStatus(401);
            return false;
        }
        //验证成功放行,将用户数据存入ThreadLocal中
        Claims claims = JwtUtils.getClaims(token);
        String mobile = (String)claims.get("mobile");
        Integer id = (Integer) claims.get("id");
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        UserHolder.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
